package net.maergaiyun.controller;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.maergaiyun.enums.ProductOrderPayTypeEnum;
import net.maergaiyun.service.ProductOrderService;
import net.maergaiyun.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/callback/order/v1/")
@Slf4j
public class PayCallbackController {
    @Autowired
    private ProductOrderService productOrderService;

    @RequestMapping("wechat")
    @ResponseBody
    public Map<String, String> wechatPayCallback(HttpServletRequest request, HttpServletResponse response) {
        String body = getRequestBody(request);
        Map<String, String> resultMap = new HashMap<>(2);
        try {
            Map<String, String> paramsMap = convertWechatPayMsgToMap(body);

            JsonData jsonData = productOrderService.processOrderCallBackMsg(ProductOrderPayTypeEnum.WECHAT_PAY, paramsMap);
            resultMap.put("code", "SUCCESS");
            resultMap.put("message", "成功");
        } catch (Exception e) {

        }

        return resultMap;
    }

    private Map<String, String> convertWechatPayMsgToMap(String body) {
        Map<String, String> paramsMap = new HashMap<>();
        JSONObject jsonObject = JSONObject.parseObject(body);
        paramsMap.put("out_trade_no", jsonObject.getString("out_trade_no"));
        paramsMap.put("trade_state", jsonObject.getString("trade_state"));
        paramsMap.put("account_no", jsonObject.getJSONObject("attach").getString("accountNo"));

        return paramsMap;
    }

    /**
     * 读取请求数据流
     *
     * @param request
     * @return
     */
    private String getRequestBody(HttpServletRequest request) {
        StringBuffer sb = new StringBuffer();
        try (ServletInputStream inputStream = request.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            String line;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            log.error("读取数据流异常: {}", e.toString());
        }
        return sb.toString();
    }
}
